<template>
  <div class="admin-info-container">
    <el-card shadow="hover" class="info-card">
      <template #header>
        <div class="card-header">
          <span>管理员信息</span>
          <el-button
              type="primary"
              size="small"
              @click="handleEdit"
              :loading="loading.edit"
          >
            编辑信息
          </el-button>
        </div>
      </template>

      <el-skeleton :rows="5" animated v-if="loading.info" />

      <template v-else>
        <el-descriptions :column="1" border>
          <el-descriptions-item label="管理员ID">{{ adminData.id }}</el-descriptions-item>
          <el-descriptions-item label="用户名">{{ adminData.username }}</el-descriptions-item>
          <el-descriptions-item label="姓名">{{ adminData.realName || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{ adminData.phone || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ adminData.email || '未设置' }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(adminData.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="最后登录时间">{{ formatDate(adminData.lastLoginTime) }}</el-descriptions-item>
        </el-descriptions>

        <el-dialog v-model="dialogVisible" title="编辑信息" width="50%">
          <el-form :model="editForm" label-width="100px">
            <el-form-item label="姓名">
              <el-input v-model="editForm.realName" />
            </el-form-item>
            <el-form-item label="手机号">
              <el-input v-model="editForm.phone" />
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="editForm.email" />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit" :loading="loading.edit">
              确认修改
            </el-button>
          </template>
        </el-dialog>
      </template>
    </el-card>

    <el-card shadow="hover" class="password-card" v-if="!loading.info">
      <template #header>
        <div class="card-header">
          <span>密码修改</span>
        </div>
      </template>

      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef">
        <el-form-item label="旧密码" prop="oldPassword">
          <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
          />
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              @click="submitPasswordChange"
              :loading="loading.password"
          >
            修改密码
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage} from 'element-plus'
import {getAdminInfo, updateAdminInfo, changeAdminPassword} from '@/api/admin'

// 数据状态
const adminData = ref({})
const loading = reactive({
  info: true,
  edit: false,
  password: false
})
const dialogVisible = ref(false)

// 编辑表单
const editForm = reactive({
  realName: '',
  phone: '',
  email: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const passwordFormRef = ref()

// 密码验证规则
const passwordRules = {
  oldPassword: [
    {required: true, message: '请输入旧密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
  ],
  newPassword: [
    {required: true, message: '请输入新密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
  ],
  confirmPassword: [
    {required: true, message: '请确认密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return '暂无记录'
  return new Date(timestamp).toLocaleString()
}

// 获取管理员信息
const fetchAdminInfo = async () => {
  try {
    loading.info = true
    const res = await getAdminInfo()
    adminData.value = res.data

    // 初始化编辑表单
    Object.assign(editForm, {
      realName: res.data.realName || '',
      phone: res.data.phone || '',
      email: res.data.email || ''
    })
  } catch (error) {
    ElMessage.error('获取管理员信息失败: ' + (error.message || error))
  } finally {
    loading.info = false
  }
}

// 打开编辑对话框
const handleEdit = () => {
  dialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    loading.edit = true
    await updateAdminInfo(editForm)
    await fetchAdminInfo() // 刷新数据
    ElMessage.success('信息更新成功')
    dialogVisible.value = false
  } catch (error) {
    ElMessage.error('更新失败: ' + (error.message || error))
  } finally {
    loading.edit = false
  }
}

// 提交密码修改
const submitPasswordChange = async () => {
  try {
    await passwordFormRef.value.validate()

    loading.password = true
    await changeAdminPassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    ElMessage.success('密码修改成功')
    passwordFormRef.value.resetFields()
  } catch (error) {
    if (error.fields) return // 表单验证错误
    ElMessage.error('密码修改失败: ' + (error.message || error))
  } finally {
    loading.password = false
  }
}

// 初始化加载数据
onMounted(() => {
  fetchAdminInfo()
})
</script>

<style scoped>
.admin-info-container {
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

.info-card, .password-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
}

.el-descriptions {
  margin-top: 20px;
}

.el-form {
  margin-top: 20px;
}
</style>